package com.goldsprite.gameframeworks.assets;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectMap;

public class GameAssetManager implements Disposable {
	private static GameAssetManager instance;

	private final ObjectMap<GameRes, MTexture> textures = new ObjectMap<>();
	private final ObjectMap<MTexture, GameRes> reverseTextures = new ObjectMap<>(); // 反向映射

	private GameAssetManager() {
		newColorMTexture(Color.BLACK, GameRes.Black);
		newColorMTexture(Color.WHITE, GameRes.White);
		newColorMTexture(Color.GRAY, GameRes.Gray);
		newColorMTexture(Color.BLUE, GameRes.Blue);
		newColorMTexture(Color.ORANGE, GameRes.Orange);
	}

	private void newColorMTexture(Color color, GameRes res) {
		MTexture mtex = new MTexture(ColorTextureUtils.createColorTexture(color, true), res);
		textures.put(res, mtex);
		reverseTextures.put(mtex, res);
	}

	public static GameAssetManager getInstance() {
		if (instance == null) {
			instance = new GameAssetManager();
		}
		return instance;
	}

	/**
	 * 用GameRes获取材质, 如果未加载则加载
	 *
	 * @param res
	 * @return
	 */
	public MTexture getTexture(GameRes res) {
		loadTexture(res);
		return textures.get(res);
	}

	/**
	 * 用GameRes加载internal材质
	 *
	 * @param res
	 */
	public void loadTexture(GameRes res) {
		if (isLoaded(res)) return;

		MTexture texture = new MTexture(res);

		textures.put(res, texture);
		reverseTextures.put(texture, res); // 添加到反向映射
	}

	public boolean isLoaded(GameRes res) {
		return textures.containsKey(res);
	}

	@Override
	public void dispose() {
		for (MTexture texture : textures.values()) {
			texture.dispose();
		}
		textures.clear();
		reverseTextures.clear(); // 清空反向映射
	}

	public boolean existTexture(MTexture texture) {
		return reverseTextures.containsKey(texture); // 使用反向映射快速查找
	}

	public GameRes getResId(MTexture tex) {
		return reverseTextures.get(tex); // 使用反向映射快速查找
	}

	/**
	 * 移除纹理资源（如果需要）
	 *
	 * @param res 要移除的资源
	 */
	public void removeTexture(GameRes res) {
		MTexture texture = textures.get(res);
		if (texture != null) {
			textures.remove(res);
			reverseTextures.remove(texture);
			texture.dispose();
		}
	}

	public <T> T getResource(GameRes resId) {
		GameRes.GameResType type = resId.getType();
		if(type == GameRes.GameResType.Music) {
			return null;
		}
		if(type == GameRes.GameResType.Texture || type == GameRes.GameResType.Color) {
			return (T)getTexture(resId);
		}
		return null;
	}
}
